var app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx.js');
var countredraintime = null;
var timerTem = null;
var counteventtime = [];
Page({
  data: {
    memberimgUrls: [],
    advertImg: null,
    isLocate: true,
    showLoginPop: false,
    scene: null,
    datetime: '',
    isDisable: false,
    longitude: "",
    latitude: "",
    isShow: false,
    hongbaoArr: null,
    isLoading: false,
    showRedPackets: false,
    showRedPacketsClose: false,
    showRedPacketsOpen: false,
    isGetHbSuc: null,
    isGeted: false,
    isOpened: false,
    countH: '00',
    countM: '00',
    countS: '00',
    showRedRainBtn: false,
    isLogin: false,
    location: '定位中...',
    logoMtop: 0, //距离顶部距离
    menuBtnBottom: 58,
    showTopPop: true,
    advertList: [], //门店分类列表广告位
    advertLeft: [], //左侧特殊广告位
    advertRight: [], //右侧特殊广告位
    storeInfo: '',
    isFixed: false,
    title: "",
    duration: 0, //水平滚动方法一中文字滚动总时间
    isDisableLog: false,
    isShowBack: true,
    eventTagList: [],
    curEventTag: 0,
    curPath: "", //用于埋点统计
    curPathName: "", //用于埋点统计
    curEvendId: "", //用于埋点统计
    popImg: "",
    isRemarked: false,
    showPopImg: false,
    timestap: Date.parse(new Date())
  },
  onLoad(options = {}) {
    // wx.showTabBarRedDot({
    //   index: 1
    // })
    app.globalData.isLocate = true;
    if (options.scene != undefined) {
      this.data.scene = options.scene;
      app.globalData.scene = options.scene;
      console.log(options.scene)
    }
    if (app.globalData.isLocate) {
      this.setData({
        isLocate: app.globalData.isLocate
      })
    }
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      wx.setBackgroundColor({
        backgroundColor: '#fff', // 顶部窗口的背景色为
        backgroundColorBottom: '#fff' // 底部窗口的背景色为白色
      })
      console.log(wx.getMenuButtonBoundingClientRect())
      this.setData({
        logoMtop: wx.getMenuButtonBoundingClientRect().top == 0 ? 20 : wx.getMenuButtonBoundingClientRect().top,
        menuBtnBottom: wx.getMenuButtonBoundingClientRect().top == 0 ? 58 : wx.getMenuButtonBoundingClientRect().bottom,
      })
    }
    this.setData({
      isShowBack: app.globalData.wxversion > 700 ? true : false
    })
  },
  onPageScroll: function () {
    this.setData({
      showTopPop: false
    })
    wx.createSelectorQuery().select('.member-tit').boundingClientRect(res => {
      if (res!= null && res.bottom <= 0) {
        this.setData({
          isFixed: true
        })
      } else {
        this.setData({
          isFixed: false
        })
      }
    }).exec()
  },
  onHide() {
    app.globalData.isRemarked = true;
    this.data.scene = "";
    this.setData({
      showRedPackets: false,
      showTopPop: false
    })
    for (var i = 0; i < this.data.memberimgUrls.length; i++) {
      clearTimeout(counteventtime[i]);
    }
    clearTimeout(countredraintime);
  },
  onUnload() {
    this.data.scene = "";
    this.setData({
      showRedPackets: false
    })
    for (var i = 0; i < this.data.memberimgUrls.length; i++) {
      clearTimeout(counteventtime[i]);
    }
    clearTimeout(countredraintime);
  },
  onShow() {
    if (app.globalData.isLocate) {
      this.setData({
        isLocate: app.globalData.isLocate,
        isRemarked: app.globalData.isRemarked
      })
      if (app.globalData.locateCity == "" || app.globalData.city == "" || app.globalData.longitude == null || app.globalData.latitude == null) {
        this.locateCur();
        app.globalData.refreshTag = true;
      } else {
        app.globalData.refreshTag = app.globalData.isChangeIndexLocation ? true : false;
        this.setData({
          location: app.globalData.location
        })
        if (this.data.scene != null) {
          if ((this.data.scene).indexOf('DECODE') > -1) {
            this.decodeScene(this.data.scene);
          } else if (this.data.scene == 'REFRIGERATOR_STICKER') {
            common.checkLogin().then(res => {
              this.setData({
                packetUrl: '/voucher/hascouponlist/',
                packetScene: 'REFRIGERATOR_STICKER'
              })
              if (res.errno == "0") {
                app.globalData.isGetWxUserinfo = true;
                this.setData({
                  showLoginPop: false
                })
                this.selectComponent("#redPacketsPool").showRedPackets();
                wx.setStorage({
                  key: "sso",
                  data: res.data.sso,
                  success: res => {}
                })
                if (JSON.stringify(res.data.member) != "{}") {
                  this.storageUserinfo(res.data);
                }
              } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
                this.setData({
                  showLoginPop: true
                })
              } else {
                common.showErrorToast(res.errmsg)
              }
            })
          }
        }
        this.getRedbagPop();
        this.getBanner();
        this.getStoreBanner();
        this.getTagList();
      }
    }
  },

  //下拉刷新
  onPullDownRefresh() {
    if (app.globalData.locateCity == "" || app.globalData.city == "") {
      this.locateCur();
    } else {
      if (this.data.scene != null) {
        if ((this.data.scene).indexOf('DECODE') > -1) {
          this.decodeScene(this.data.scene);
        } else if (this.data.scene == 'REFRIGERATOR_STICKER') {
          common.checkLogin().then(res => {
            this.setData({
              packetUrl: '/voucher/hascouponlist/',
              packetScene: 'REFRIGERATOR_STICKER'
            })
            if (res.errno == "0") {
              app.globalData.isGetWxUserinfo = true;
              this.setData({
                showLoginPop: false
              })
              this.selectComponent("#redPacketsPool").showRedPackets();
              wx.setStorage({
                key: "sso",
                data: res.data.sso,
                success: res => {}
              })
              if (JSON.stringify(res.data.member) != "{}") {
                this.storageUserinfo(res.data);
              }
            } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
              this.setData({
                showLoginPop: true
              })
            } else {
              common.showErrorToast(res.errmsg)
            }
          })
        }
      }
      for (var i = 0; i < this.data.memberimgUrls.length; i++) {
        clearTimeout(counteventtime[i]);
      }
      this.getRedbagPop();
      this.getBanner();
      this.getStoreBanner();
      this.getTagList();
    }
    clearTimeout(countredraintime);
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      wx.setBackgroundTextStyle({
        textStyle: 'light' // 下拉背景字体、loading 图的样式为dark
      })
    }
  },
  // 获取定位
  locateCur() {
    var that = this;
    common.showLoading();
    var gdMap = new amapFile.AMapWX({
      key: common.gdKey
    });
    gdMap.getRegeo({
      success: resp => {
        common.hideLoading();
        app.globalData.locateLongitude = resp[0].longitude;
        app.globalData.locateLatitude = resp[0].latitude;
        app.globalData.locateCity = resp[0].regeocodeData.addressComponent.city;
        app.globalData.locateProvince = resp[0].regeocodeData.addressComponent.province;
        if (app.globalData.longitude == null || app.globalData.latitude == null || app.globalData.location == null) {
          app.globalData.skipType = 1;
          app.globalData.longitude = resp[0].longitude;
          app.globalData.latitude = resp[0].latitude;
          app.globalData.location = resp[0].regeocodeData.pois[0] == undefined ? resp[0].name : resp[0].regeocodeData.pois[0].name;
          app.globalData.city = resp[0].regeocodeData.addressComponent.city;
        }
        that.setData({
          location: app.globalData.location
        })
        that.getRedbagPop();
        if (that.data.scene != null) {
          if ((that.data.scene).indexOf('DECODE') > -1) {
            that.decodeScene(that.data.scene);
          } else if (that.data.scene == 'REFRIGERATOR_STICKER') {
            common.checkLogin().then(res => {
              that.setData({
                packetUrl: '/voucher/hascouponlist/',
                packetScene: 'REFRIGERATOR_STICKER'
              })
              if (res.errno == "0") {
                app.globalData.isGetWxUserinfo = true;
                that.setData({
                  showLoginPop: false
                })
                that.selectComponent("#redPacketsPool").showRedPackets();
                wx.setStorage({
                  key: "sso",
                  data: res.data.sso,
                  success: res => {}
                })
                if (JSON.stringify(res.data.member) != "{}") {
                  that.storageUserinfo(res.data);
                }
              } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
                that.setData({
                  showLoginPop: true
                })
              } else {
                common.showErrorToast(res.errmsg)
              }
            })
          }
        }
        that.getBanner();
        that.getStoreBanner();
        that.getTagList();
      },
      fail: info => {
        that.setData({
          isLocate: false,
          showLoginPop: false
        })
        common.hideLoading();
        app.globalData.isLocate = false
      }
    })
    wx.stopPullDownRefresh();
  },
  //banner轮播跳转
  goToUrl(e) {
    var curtarget = e.currentTarget.dataset;
    if (curtarget.appid != "" && curtarget.pathurl != "") { //跳转小程序
      wx.navigateToMiniProgram({
        appId: curtarget.appid,
        path: curtarget.pathurl,
        success: res => {
          console.log("成功打开!")
        },
        fail: res => {}
      })
    } else if (curtarget.appid == "" && curtarget.pathurl != "") { //跳转公众号文章
      this.data.curPath = curtarget.pathurl;
      wx.navigateTo({
        url: '../common/gzh?url=' + encodeURIComponent(curtarget.pathurl),
      })
    } else { //跳转小程序内部页面
      this.data.curPath = curtarget.path;
      this.data.curPathName = curtarget.name;
      var path = curtarget.path;
      if (path.indexOf('url') > -1) {
        wx.navigateTo({
          url: path.split("url=")[1],
        })
      } else if (path.indexOf('store') > -1) {
        if (path.indexOf('store_category') > -1) {
          var query = path.split("?")[1];
          wx.navigateTo({
            url: '../shop/productsListIndex?' + query,
          })
        } else {
          wx.navigateTo({
            url: '../shop/productsListIndex',
          })
        }
      }
    }
  },
  //获取用户信息
  getUserInfo() {
    if (this.data.isLogin) {
      this.showRedPackets();
    } else {
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              this.setData({
                showLoginPop: false
              })
              var code = resp.code,
                that = this,
                userParams = {
                  "js_code": code,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userinfo": res.userInfo,
                  "longitude": app.globalData.locateLongitude,
                  "latitude": app.globalData.locateLatitude,
                  "province": app.globalData.locateProvince,
                  "city": app.globalData.locateCity,
                  "scene": this.data.scene
                };
              server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.stopPullDownRefresh();
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: ret => {
                      that.data.isLogin = true;
                      that.showRedPackets();
                      if (JSON.stringify(res.data.data.member) != "{}") {
                        app.globalData.openid = res.data.data.openid;
                        that.storageUserinfo(res.data.data)
                      }
                    }
                  })
                } else {
                  common.showErrorToast(res.data.errmsg);
                }
              })
            },
            fail: res => {
              wx.removeStorage({
                key: 'userInfo',
                success: function (res) {
                  console.log(res.data)
                }
              })
              this.setData({
                showLoginPop: true
              })
            }
          })
        }
      })
    }
  },
  //授权用户信息
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false
      })
      var that = this
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code,
                that = this,
                userParams = {
                  "js_code": code,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userinfo": res.userInfo,
                  "longitude": app.globalData.locateLongitude,
                  "latitude": app.globalData.locateLatitude,
                  "province": app.globalData.locateProvince,
                  "city": app.globalData.locateCity,
                  "scene": this.data.scene
                }
              server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: ret => {
                      that.setData({
                        isDisableLog: false
                      })
                      if (((that.data.scene).indexOf('DECODE') > -1 || that.data.scene == 'REFRIGERATOR_STICKER') && that.data.packetScene != '' && that.data.packetUrl != '') {
                        that.selectComponent("#redPacketsPool").showRedPackets();
                      }
                      if (JSON.stringify(res.data.data.member) != "{}") {
                        app.globalData.openid = res.data.data.openid;
                        that.storageUserinfo(res.data.data)
                      }
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  //获取会员专供banner
  getEventBanner() {
    wx.stopPullDownRefresh();
    console.log(app.globalData.city)
    server.login(common.storePath + 'event/list/', {
      "city": app.globalData.city,
      "tag_id": this.data.curEventTag
    }, res => {
      if (res.data.errno == "0") {
        let data = res.data.data;
        this.setData({
          memberimgUrls: JSON.stringify(data) == "{}" ? [] : data
        })
        if (data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            clearTimeout(counteventtime[i]);
          }
          for (var i = 0; i < data.length; i++) {
            this.setData({
              ['memberimgUrls[' + i + '].counttime']: '00:00:00'
            })
            if (data[i].status == 'going' || data[i].status == 'end') {
              this.countEventTime(data[i].end_time, i, data[i].status)
            } else if (data[i].status == 'wait') {
              this.countEventTime(data[i].start_time, i, data[i].status)
            }
          }
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },

  //会员专供详情
  goToEventDetail(e) {
    var evendId = e.currentTarget.dataset.id,
      template_id = e.currentTarget.dataset.templateid,
      goodsid = e.currentTarget.dataset.goodsid;
    this.data.curEvendId = e.currentTarget.dataset.id;
    this.data.curPath = e.currentTarget.dataset.name;
    if (template_id != '0') {
      wx.navigateTo({
        url: '../../membership_supply/pages/productListsM' + template_id + '?eventid=' + evendId
      })
    } else {
      wx.navigateTo({
        url: '../../membership_supply/pages/productDetailM?eventid=' + evendId + '&&goodsid=' + goodsid
      })
    }
  },
  // 获取banner
  getBanner() {
    var that = this;
    wx.stopPullDownRefresh();
    server.login(common.storePath + 'advert/getfirstpopbanner/', {
      "city": app.globalData.city
    }, function (res) {
      if (res.data.errno == "0") {
        let data = res.data.data;
        that.setData({
          roll: data.roll,
          title: data.title,
          popImg: data.pop_url
        })
        wx.getStorage({
          key: 'sso',
          success: resp => {
            server.postJSON(common.basePath + 'user/isshow', {
              "type": "znq",
              "is_checked": 0
            }, res => {
              if (res.data.errno == '0') {
                that.setData({
                  showPopImg: res.data.data == 1 ? true : false
                })
              } else {
                if (res.data.errno != "100013") {
                  common.showErrorToast(res.data.errmsg);
                }
              }
            })
          },
          fail: res => {
            that.setData({
              showPopImg: true
            })
          }
        })
        if (data.title != '') {
          wx.createSelectorQuery().select('#txt1').boundingClientRect(function (rect) {
            let duration = rect.width * 0.03; //滚动文字时间,滚动速度为0.03s/px
            that.setData({
              duration: duration
            })
          }).exec();
          wx.createSelectorQuery().select('.notice-cont').boundingClientRect(function (res) {
            that.setData({
              noticeTop: res.top
            })
          }).exec()
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 获取门店分类广告位
  getStoreBanner() {
    var that = this;
    wx.stopPullDownRefresh();
    var storeId = wx.getStorageSync('storeId');
    app.globalData.skipType = storeId == undefined ? app.globalData.skipType : 2;
    server.postJSON(common.storePath + 'advert/getstoreadvert/', {
      "city": app.globalData.city,
      "store_id": storeId == undefined || storeId == '' ? 0 : storeId,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude,
    }, function (res) {
      if (res.data.errno == "0") {
        let data = res.data.data;
        that.setData({
          advertLeft: data.advert_left,
          advertRight: data.advert_right,
          storeInfo: data.store,
          advertList: data.advert_list
        })
        wx.setStorage({
          key: 'storeId',
          data: data.store.store_id,
        })
      } else {
        that.setData({
          storeInfo: ''
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.locateCur();
      app.globalData.refreshTag = true;
      wx.stopPullDownRefresh();

    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  //分享事件
  onShareAppMessage(option) {
    var that = this;
    var shareObj = {
      imageUrl: '../../imgs/share.jpg',
      path: '/pages/index/index',
      title: '健康三餐，1小时送到家'
    }
    return shareObj;
  },
  //解析scene
  decodeScene(scene) {
    server.postJSON(common.storePath + 'voucher/scenedecode/', {
      "scene": scene
    }, res => {
      var data = res.data;
      if (data.errno == '0') {
        wx.setStorage({
          key: 'companyid',
          data: data.data.company_id,
        })
        if (data.data.store_id != '' && data.data.store_id != '0') {
          wx.setStorage({
            key: 'storeId',
            data: data.data.store_id,
          })
          app.globalData.longitude = app.globalData.locateLongitude;
          app.globalData.latitude = app.globalData.locateLatitude;
          app.globalData.city = app.globalData.locateCity;
          app.globalData.skipType = 2;
        }
        if (data.data.channel_id != '') {
          wx.setStorage({
            key: 'channelid',
            data: data.data.channel_id
          })
        }
        //红包池
        this.setData({
          packetScene: data.data.company_id,
          packetUrl: data.data.url
        })
        if (this.data.packetScene != '' && this.data.packetUrl != '') {
          app.globalData.isRemarked = true;
          this.setData({
            isRemarked: true
          })
          common.checkLogin().then(res => {
            if (res.errno == "0") {
              app.globalData.isGetWxUserinfo = true;
              this.setData({
                showLoginPop: false
              })
              this.selectComponent("#redPacketsPool").showRedPackets();
              wx.setStorage({
                key: "sso",
                data: res.data.sso,
                success: res => {}
              })
              if (JSON.stringify(res.data.member) != "{}") {
                this.storageUserinfo(res.data);
              }
            } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
              this.setData({
                showLoginPop: true
              })
            } else {
              common.showErrorToast(res.errmsg)
            }
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  //红包雨动画
  getHongbao: function (i) {
    var shijian = Math.floor(Math.random() * (200 - 100) + 100); //每生成一个红包需要等待多少毫秒的时间才会生成下一个红包
    var jiaodu = Math.ceil(Math.random() * 30) - 15;
    var marginLeft = Math.ceil(Math.random() * 590);
    var animation = Math.floor(Math.random() * (6 - 3) + 3);
    var srcList = ["../../imgs/redPacket/i_redpacket.png"];
    var hongbao = {
      id: i,
      marginleft: marginLeft,
      animation: animation,
      jiaodu: jiaodu,
      src: srcList[Math.ceil(Math.random() * 2) - 1],
    }
    var hongbaoA = this.data.hongbaoArr;
    if (hongbaoA == null) {
      hongbaoA = new Array();
    }
    hongbaoA.push(hongbao);
    this.setData({
      hongbaoArr: hongbaoA
    })
    var that = this;
    if (i <= 100) {
      timerTem = setTimeout(function () {
        i = i + 1;
        that.getHongbao(i)
      }, shijian)
    } else {
      this.setData({
        showRedPackets: false
      })
    }
  },
  getRedbagPop() {
    server.postJSON(common.storePath + 'voucher/countdown/', "", res => {
      if (res.data.errno == '0') {
        var data = res.data.data;
        if (data.status == 1) {
          this.setData({
            showRedRainBtn: true,
            leftTime: data.next_time
          })
        }
        if (this.data.leftTime > 0 && this.data.leftTime <= 3000) {
          this.countTime();
        } else {
          this.setData({
            leftTime: 0
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  showRedPackets() {
    clearTimeout(countredraintime);
    this.setData({
      hongbaoArr: []
    })
    server.postJSON(common.storePath + 'voucher/redrain/', {
      "scene": this.data.scene,
      "city": app.globalData.locateCity
    }, res => {
      if (res.data.errno == '0') {
        var data = res.data.data;
        this.setData({
          hbLists: data.voucher_list,
          last_count: data.last_count,
          redbagmsg: data.msg,
          leftTime: data.next_time
        })
        if (this.data.leftTime > 0 && this.data.leftTime <= 3000) {
          this.countTime();
        } else {
          this.setData({
            leftTime: 0
          })
        }
        this.showRedRain();
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  showRedRain() {
    if (this.data.leftTime == 0 && this.data.last_count > 0) {
      this.setData({
        showRedRain: true
      })
      if (this.data.hbLists.length > 0) {
        this.getHongbao(1);
        this.setData({
          showRedPackets: true,
          showRedRain: false
        })
      } else {
        common.showErrorToast("本次红包已参与，请下一个整点再来！")
        this.setData({
          showRedPackets: false
        })
      }
    } else if (this.data.leftTime == 0 && this.data.last_count == 0) {
      common.showErrorToast(this.data.redbagmsg)
    } else if (this.data.leftTime < 3000 && this.data.last_count > 0) {
      common.showErrorToast("活动还没开始，请整点再来")
    }
  },
  getRedPacket() {
    this.setData({
      isGeted: true
    })
    server.postJSON(common.storePath + 'voucher/sendred/', { //接口切换
      "voucher_id": this.data.hbLists[0].voucher_id,
      "amount": this.data.hbLists[0].amount,
      "is_new": this.data.hbLists[0].is_new,
      "city": app.globalData.locateCity
    }, res => {
      if (res.data.errno == '0') {
        clearTimeout(timerTem);
        this.setData({
          showRedPacketsClose: true,
          isGetHbSuc: true,
          redbagTime: res.data.data.datetime,
          isGeted: false,
          isCurPage: false
        })
        this.getRedbagPop();
      } else {
        this.setData({
          showRedPacketsClose: false,
          showRedPackets: false,
          isGeted: false
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  hideRedPacket() {
    this.setData({
      showRedPackets: false,
      showRedPacketsClose: false,
      isGetHbSuc: false
    })
  },
  // 会员专供倒计时
  countEventTime(endtime, index, status) {
    var stime = Date.parse(new Date()) / 1000,
      endtime = endtime,
      status = status,
      index = index;
    var leftTime = endtime - stime;
    var d, h, m, s;
    d = Math.floor(leftTime / 60 / 60 / 24);
    if (leftTime > 0) {
      h = d * 24 + Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    } else if (leftTime <= 0) {
      if (status == 'going' || status == 'wait') {
        h = 0;
        m = 0;
        s = 0;
        this.getEventBanner();
      } else {
        h = 0;
        m = 0;
        s = 0;
      }
    }
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    if (d <= 0) {
      this.data.memberimgUrls[index].counttime = h + ':' + m + ':' + s;
      this.setData({
        memberimgUrls: this.data.memberimgUrls
      })
    } else {
      this.data.memberimgUrls[index].counttime = d + '天';
      this.setData({
        memberimgUrls: this.data.memberimgUrls
      })

    }
    var that = this;
    counteventtime[index] = setTimeout(function () {
      that.countEventTime(endtime, index, status);
    }, 1000);
  },
  // 抢红包倒计时
  countTime() {
    //时间差  
    var leftTime = this.data.leftTime;
    //定义变量 d,h,m,s保存倒计时的时间  
    var h, m, s;
    if (leftTime > 0) {
      h = Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    } else if (leftTime == 0) {
      this.showRedRain()
    }
    //将0-9的数字前面加上0，例1变为01
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    //将倒计时赋值到div中  
    if (leftTime > 0) {
      this.setData({
        countH: h,
        countM: m,
        countS: s,
      })
    }
    var that = this;
    countredraintime = setTimeout(function () {
      that.data.leftTime = parseInt(that.data.leftTime) - 1;
      that.setData({
        leftTime: that.data.leftTime
      })
      that.countTime();
    }, 1000);
  },
  getFormid(e) {
    var eventid = e.currentTarget.dataset.id;
    server.postJSON(common.basePath + 'miniprogram/getnewtemplateid', {
      "type": "event_book"
    }, res => {
      if (res.data.errno == '0') {
        var ids = [];
        (res.data.data).forEach((item, index) => {
          ids.push(item)
        })
        var that = this;
        if (app.globalData.sdkversion >= 282 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
          wx.requestSubscribeMessage({
            tmplIds: ids,
            success(resp) {
              if (resp[ids[0]] == 'accept') {
                server.postJSON(common.storePath + 'event/book/', {
                  "event_id": eventid,
                  "form_id": 1
                }, ret => {
                  if (ret.data.errno == '0') {
                    common.showErrorToast("将在活动开始前通过微信通知您")
                  } else {
                    common.showErrorToast(ret.data.errmsg)
                  }
                })
              } else {
                console.log(res)
              }
            },
            fail(resp) {
              console.log(resp)
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用订阅消息通知功能，请升级到最新微信版本后重试。',
            success(res) {
              console.log('用户点击确定');
            }
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  goToChangeAddr() {
    wx.navigateTo({
      url: 'changeIndexLocation',
    })
  },
  goToChangeStore() {
    wx.navigateTo({
      url: '../../shop/pages/changeStore',
    })
  },
  getTagList() {
    server.login(common.storePath + 'event/tag/', {
      "city": app.globalData.city
    }, res => {
      if (res.data.errno == "0") {
        let data = res.data.data;
        this.setData({
          eventTagList: data,
          curEventTag: data[0].tag_id
        })
        this.getEventBanner();
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  changeEventTag(e) {
    for (var i = 0; i < this.data.memberimgUrls.length; i++) {
      clearTimeout(counteventtime[i]);
    }
    clearTimeout(countredraintime);
    this.setData({
      curEventTag: e.currentTarget.dataset.tagid
    })
    this.getEventBanner();
  },
  goToProductIndex() {
    wx.navigateTo({
      url: '../shop/productsListIndex',
    })
  },
  closePopImg() {
    this.setData({
      isRemarked: true
    })
    app.globalData.isRemarked = true;
  },
  goToActivityLandPage() {
    wx.navigateTo({
      url: '../../activity/pages/activity_advert',
    })
    this.setData({
      isRemarked: true
    })
    app.globalData.isRemarked = true;
  },
  goToSearch() {
    wx.navigateTo({
      url: '../../shop/pages/searchProduct',
    })
  },
  goToIndex() {
    console.log('index')
  }
});